package com.eclipsemail.core.authentication.impl;

import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;

import com.eclipsemail.core.authentication.Auth;
import com.eclipsemail.core.authentication.Authenticable;
import com.eclipsemail.core.authentication.AuthenticationException;
import com.google.common.base.Preconditions;

public class GMailAuthentication implements Authenticable {

    private static final String IMAP = "imap.gmail.com";

    private final Auth auth;

    private Store store;

    public GMailAuthentication(Auth auth) {
        this.auth = Preconditions.checkNotNull(auth);
    }

    @Override
    public Auth getAuth() {
        return auth;
    }

    @Override
    public Store connect(Session session) throws AuthenticationException {
        try {
            store = session.getStore("imaps");
            store.connect(IMAP, auth.getLogin(), new String(auth.getPass()));
        } catch (NoSuchProviderException e) {
            throw new AuthenticationException(e);
        } catch (MessagingException e) {
            throw new AuthenticationException(e);
        }
        return store;
    }

    @Override
    public void close() {
        if (store != null) {
            try {
                store.close();
                store = null;
            } catch (MessagingException e) {
                // Discard.
                // TODO: logger
            }
        }
    }

}
